#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define SERVER_PORT    8888      /*服务器端口号*/
#define SERVER_IP      "192.168.1.132"  /*服务器IP*/

int main()
{
    int sockfd;
    struct sockaddr_in server_addr = {0};
    int ret;
    char buf[512];

    /*1.打开套接字*/
    sockfd =  socket(AF_INET, SOCK_STREAM, 0);
    if(-1 == sockfd){
        perror("socket error");
        exit(EXIT_FAILURE);
    }

    /*2.connect连接服务器*/
    server_addr.sin_family = AF_INET;
    server_addr.sin_port = htons(SERVER_PORT);
    inet_pton(AF_INET, SERVER_IP, &server_addr.sin_addr);

    ret = connect(sockfd, (const struct sockaddr *)&server_addr,sizeof(server_addr));
    if(ret == -1){
        perror("connect error");
        close(sockfd);
        exit(EXIT_FAILURE);
    }

    printf("服务器连接成功...\n\n");

    /*向服务器发数据*/
    for(;;){

        /*清理缓存*/
        memset(buf,0,sizeof(buf));

        printf("Please enter a string:");
        fgets(buf,sizeof(buf),stdin);

        /*发送数据到服务器*/
        ret = send(sockfd,buf,strlen(buf),0);
        if(-1 == ret){
            perror("send error");
            break;
        }

        /*输入了"quit"，推出程序*/
        if(!strncmp(buf,"quit",4))
            break;
    }

    close(sockfd);
    exit(EXIT_SUCCESS);
}
